﻿Imports MvcMusicStoreVB.Models

Namespace Controllers
    <Authorize()>
    Public Class CheckoutController
        Inherits System.Web.Mvc.Controller

        Private storeDB As MusicStoreEntities = New MusicStoreEntities
        Private Const PromoCode = "FREE"

        '
        ' GET: /Checkout/AddressAndPayment

        Function AddressAndPayment() As ActionResult
            Return View()
        End Function

        '
        ' POST: /Checkout/AddressAndPayment

        <HttpPost()>
        Function AddressAndPayment(ByVal values As FormCollection) As ActionResult
            Dim order = New Order
            TryUpdateModel(order)

            Try
                If Not String.Equals(values("PromoCode"), PromoCode, StringComparison.OrdinalIgnoreCase) Then
                    Return View(order)
                Else
                    order.Username = User.Identity.Name
                    order.OrderDate = DateTime.Now

                    'Save Order
                    storeDB.Orders.Add(order)
                    storeDB.SaveChanges()
                    'process the order
                    Dim cart = ShoppingCart.GetCart(HttpContext)
                    cart.CreateOrder(order)

                    Return RedirectToAction("Complete", New With {.id = order.OrderId})
                End If
            Catch ex As Exception
                'invalid - redisplay with errors
                Return View(order)
            End Try
        End Function

        '
        ' GET: /Checkout/Complete
        Function Complete(ByVal id As Integer) As ActionResult
            Dim isValid = storeDB.Orders.Any(Function(o) o.OrderId = id AndAlso o.Username = User.Identity.Name)

            If isValid Then
                Return View(id)
            Else
                Return View("Error")
            End If
        End Function

    End Class
End Namespace